<template>
  <view class="page-container min-h-screen flex flex-col bg-gray-100" :style="{ paddingTop: `${headerHeight}px` }">
    <!-- 固定的顶部区域 -->
    <view id="fixed-header" class="fixed left-0 right-0 top-0 z-10 bg-white">
      <!-- 顶部导航 -->
      <S1Header title="赊欠订单" :on-back="onBack" />
      <!-- 搜索框（固定在头部下方） -->
      <view class="search-box border-b border-gray-200 bg-white px-4 py-2">
        <view class="mx-auto w-[330px] flex items-center justify-between">
          <view class="flex-1">
            <view
              class="h-[37px] flex items-center justify-between border border-[#e4eaf2] rounded-[18px] bg-[#f5f7fa] px-3"
              @tap="openCalendar"
            >
              <text v-if="dateRange.length > 0" class="text-sm text-gray-600">
                {{ `${dateRange[0]} 至 ${dateRange[1]}` }}
              </text>
              <text v-else class="text-gray-400">
                选择日期范围
              </text>
              <view class="flex items-center">
                <text v-if="dateRange.length <= 0" class="mr-1 text-gray-400">
                  ▼
                </text>
                <text
                  v-else
                  class="i-carbon-close text-gray-400"
                  @tap.stop="clearDateRange"
                >
                  X
                </text>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
    <!-- 日历组件 -->
    <up-calendar
      :show="showCalendar"
      mode="range"
      start-text="开始"
      end-text="结束"
      color="#ff6b01"
      @confirm="onDateRangeConfirm"
      @close="closeCalendar"
    />
    <!-- 订单列表 -->
    <scroll-view scroll-y class="order-list flex-1 bg-gray-100 pb-24 pt-2">
      <!-- 订单项 -->
      <view
        v-for="order in orders"
        :key="order.id"
        class="mx-3 mb-3 overflow-hidden rounded-lg bg-white shadow-sm"
      >
        <!-- 顶部区域: 订单信息区 -->
        <view class="px-3 pb-1 pt-2">
          <view class="mb-1 flex justify-between">
            <text class="text-sm text-[#ff6b01] font-medium">
              #{{ order.id }}
            </text>
            <text class="text-xs text-gray-400">
              {{ formatDate(order.add_time) }} 开票员：{{ getUserName(order) }}
            </text>
          </view>
        </view>

        <!-- 内容和按钮并排区域 -->
        <view class="flex px-3 pb-2">
          <!-- 左侧内容区（带红边框） -->
          <view class="mr-2 flex-1 border border-[#ff6b01] rounded p-1.5">
            <view class="flex">
              <!-- 复选框 -->
              <checkbox
                class="mr-2 scale-80 transform"
                :checked="selectedOrders.includes(order.id)"
                color="#ff6b01"
                @tap="toggleOrderSelection(order)"
              />

              <!-- 内容区 -->
              <view class="flex-1">
                <view class="mb-1 flex justify-between">
                  <text class="font-medium">
                    {{ order.maijia }}
                  </text>
                  <text class="text-sm text-[#ff6b01]">
                    下欠金额：
                    <text class="text-[#ff6b01]">
                      {{ formatNumber(order.print_price || 0) }}
                    </text>
                  </text>
                </view>
                <view class="flex justify-between">
                  <text class="block truncate pr-2 text-xs text-gray-400">
                    {{ formatOrderDetail(order.order_detail) }}
                  </text>
                  <text class="whitespace-nowrap text-xs text-gray-400">
                    共{{ order.order_detail?.length || 0 }}种商品
                  </text>
                </view>
              </view>
            </view>
          </view>

          <!-- 右侧按钮区 -->
          <view class="flex flex-col justify-center">
            <button
              :id="`share-btn-${order.id}`"
              class="mb-1.5 w-14 rounded-sm bg-[#4292eb] px-0 py-1 text-xs text-white"
              :class="{ 'opacity-60': order.isGeneratingImage }"
              open-type="share"
              :data-order-index="orders.indexOf(order)"
            >
              {{ order.isGeneratingImage ? '生成中...' : '分享' }}
            </button>
            <button
              class="w-14 rounded-sm bg-[#eb7a42] px-0 py-1 text-xs text-white"
              @tap="handleView(order)"
            >
              查看
            </button>
          </view>
        </view>
      </view>

      <!-- 加载状态 -->
      <view
        v-if="orders.length === 0 && !loading"
        class="load-tip py-3 text-center text-xs text-gray-400"
      >
        暂无数据
      </view>
      <view
        v-if="loading"
        class="load-tip py-3 text-center text-xs text-gray-400"
      >
        加载中...
      </view>
      <view
        v-if="orders.length > 0 && !loading"
        class="load-tip py-3 text-center text-xs text-gray-400"
      >
        已加载全部数据
      </view>
    </scroll-view>

    <!-- Canvas 画布用于绘制分享图片 -->
    <canvas
      canvas-id="shareCanvas"
      :style="{
        width: `${canvasWidth}px`,
        height: `${canvasHeight}px`,
        position: 'fixed',
        right: '-999999px',
      }"
    />

    <!-- 底部工具栏 -->
    <view
      v-if="orders.length > 0"
      class="footer-bar fixed bottom-0 left-0 right-0 h-[110rpx] flex items-center justify-between border-t border-t-[#eee] bg-white"
    >
      <view class="ml-4 flex items-center">
        <checkbox
          class="scale-80 transform"
          :checked="isAllSelected"
          color="#ff6b01"
          @tap="toggleSelectAll"
        />
        <text class="ml-2 text-sm">
          全选
        </text>

        <view class="ml-2">
          <text class="block text-xs">
            已选
            <text class="text-[#ff6b01]">
              {{ selectedOrders.length }}
            </text>
            笔
          </text>
          <text class="block text-xs">
            共
            <text class="text-[#ff6b01]">
              {{ getTotalAmount() }}
            </text>
            元
          </text>
        </view>
      </view>

      <view class="mr-3 flex">
        <button
          class="h-[80rpx] rounded-[8rpx] border-none bg-[#ff6b01] px-[30rpx] text-sm text-white leading-[80rpx]"
          @tap="handleRepay"
        >
          还款
        </button>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import type { OrderCarItem } from '@/api/order/types';
import { onShareAppMessage } from '@dcloudio/uni-app';
import { computed, getCurrentInstance, nextTick, ref, watch } from 'vue';
import { getOrderData } from '@/api/order';
import S1Header from '@/components/S1Header.vue';
import { useUserStore } from '@/store';

// 类型定义
interface OrderDetail {
  goods_name: string;
  weight: number;
  unit: string;
  num: number;
  mini_type: string;
}

interface ExtendedOrderCarItem extends OrderCarItem {
  order_detail?: OrderDetail[];
  print_price?: number;
  user?: {
    name: string;
  };
  order_type?: string;
  imageUrl?: string;
  shareImageUrl?: string;
  isGeneratingImage?: boolean;
}

const userStore = useUserStore();

// 工具函数
const formatDate = (dateStr: string | undefined) => {
  if (!dateStr) return '-';
  try {
    const date = new Date(dateStr);
    const pad = (num: number) => String(num).padStart(2, '0');
    return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(
      date.getDate(),
    )} ${pad(date.getHours())}:${pad(date.getMinutes())}`;
  }
  catch (e) {
    return dateStr;
  }
};

const formatNumber = (num: number) => num.toLocaleString();

const formatOrderDetail = (orderDetail: OrderDetail[] | undefined): string => {
  if (!orderDetail?.length) return '暂无商品详情';
  return orderDetail
    .slice(0, 2)
    .map((item) => {
      const { goods_name, weight, unit, num, mini_type } = item;
      return mini_type === '公斤'
        ? `${goods_name} ${weight}${unit}`
        : `${goods_name} ${num}${unit}`;
    })
    .join(' ');
};

// 提示信息工具函数
const showToast = (title: string, icon: 'none' | 'success' = 'none') => {
  uni.showToast({ title, icon });
};

// 状态管理
const maijiaId = ref<number>(0);
const orders = ref<ExtendedOrderCarItem[]>([]);
const loading = ref(false);
const dateRange = ref<string[]>([]);
const showCalendar = ref(false);
const selectedOrders = ref<number[]>([]);

// Canvas 相关
const canvasWidth = ref(375);
const canvasHeight = ref(300);

// 顶部 S1Header 高度，用于给页面内容留出空间
const headerHeight = ref(0);
const measureHeader = () => {
  nextTick(() => {
    const instance = getCurrentInstance();
    const query = uni.createSelectorQuery();
    if (query) {
      // 限定当前页面上下文（H5/小程序均可正常获取）
      if ((query as any).in && instance?.proxy) {
        (query as any).in(instance.proxy);
      }
      query
        .select('#fixed-header')
        .boundingClientRect((rect: any) => {
          if (rect && rect.height) headerHeight.value = rect.height;
        })
        .exec();
    }
  });
};

// 计算属性
const isAllSelected = computed(
  () =>
    orders.value.length > 0
    && selectedOrders.value.length === orders.value.length,
);

// 监听器
watch(
  dateRange,
  (newDateRange) => {
    if (newDateRange.length === 2) loadOrderData();
  },
  { deep: true },
);

// 生命周期钩子
onLoad((options: any) => {
  maijiaId.value = options?.maijia_id || 0;
});

onShow(() => {
  measureHeader();
  loadOrderData();
  // 初始化 canvas 尺寸
  uni.getSystemInfo({
    success: (res) => {
      canvasWidth.value = res.screenWidth;
      canvasHeight.value = res.screenWidth * 0.8; // 保持 5:4 比例
    },
  });
});

// 日期相关方法
const openCalendar = () => (showCalendar.value = true);
const closeCalendar = () => (showCalendar.value = false);
const onDateRangeConfirm = (e: any) => {
  dateRange.value = [e[0], e[e.length - 1]];
  closeCalendar();
};
const clearDateRange = () => {
  dateRange.value = [];
  loadOrderData();
};

// 数据加载方法
async function loadOrderData() {
  if (!maijiaId.value) {
    showToast('买家ID不能为空');
    return;
  }

  loading.value = true;
  try {
    const res = await getOrderData({
      maijia_id: maijiaId.value,
      status: 0,
      date: dateRange.value,
    });

    if (res.code === 200 && res.data) {
      orders.value = (res.data.data as ExtendedOrderCarItem[]) || [];
    }
    else {
      showToast(res.msg || '获取数据失败');
    }
  }
  catch (error) {
    console.error('加载订单数据失败', error);
    showToast('加载失败，请重试');
  }
  finally {
    loading.value = false;
  }
}

// 订单选择相关方法
const toggleOrderSelection = (order: ExtendedOrderCarItem) => {
  const index = selectedOrders.value.indexOf(order.id);
  if (index === -1) {
    selectedOrders.value.push(order.id);
  }
  else {
    selectedOrders.value.splice(index, 1);
  }
};

const toggleSelectAll = () => {
  selectedOrders.value = isAllSelected.value
    ? []
    : orders.value.map(order => order.id);
};

const getTotalAmount = () =>
  formatNumber(
    orders.value
      .filter(order => selectedOrders.value.includes(order.id))
      .reduce((sum, order) => sum + (order.print_price || 0), 0),
  );

// 订单操作相关方法
const onBack = () => uni.navigateBack();

const handleView = (order: ExtendedOrderCarItem) => {
  // 将整个订单对象存储到本地
  uni.setStorageSync('currentOrderDetail', order);

  uni.navigateTo({
    url: `/pages/common/creditOrderDetail/index?id=${order.id}`,
  });
};

const handleRepay = () => {
  if (selectedOrders.value.length === 0) {
    showToast('请先选择订单');
    return;
  }

  const totalAmount = orders.value
    .filter(order => selectedOrders.value.includes(order.id))
    .reduce((sum, order) => sum + (order.print_price || 0), 0);

  uni.setStorageSync('repaymentData', {
    orderIds: selectedOrders.value,
    totalDebt: totalAmount,
  });

  uni.navigateTo({ url: '/pages/common/creditRepayment/index' });
};

// 在模板中使用的辅助方法
const getUserName = (order: ExtendedOrderCarItem): string =>
  order.user?.name || '-';

// 格式化日期（精确到秒）
const formatDateWithSeconds = (dateStr: string | undefined) => {
  if (!dateStr) return '-';
  try {
    const date = new Date(dateStr);
    const pad = (num: number) => String(num).padStart(2, '0');
    return `${
      date.getFullYear()
    }-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(
      date.getHours(),
    )}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
  }
  catch (e) {
    return dateStr;
  }
};

// 创建分享图片
function createShareImage(order: ExtendedOrderCarItem, index: number): Promise<string> {
  return new Promise((resolve, reject) => {
    // @ts-ignore
    const ctx = uni.createCanvasContext('shareCanvas');

    // 设置背景色
    ctx.setFillStyle('#f5fafe');
    ctx.fillRect(0, 0, canvasWidth.value, canvasHeight.value);

    // 添加边框
    ctx.setStrokeStyle('#f0f0f0');
    ctx.setLineWidth(1);
    ctx.strokeRect(0, 0, canvasWidth.value, canvasHeight.value);

    // 绘制买家名称（标题）- 加粗效果
    ctx.setFillStyle('#000000');
    ctx.setFontSize(36);
    ctx.setTextAlign('left');
    // 多次绘制模拟加粗
    ctx.fillText(order.maijia, 29, 60);
    ctx.fillText(order.maijia, 29.5, 60);
    ctx.fillText(order.maijia, 29, 60.5);
    ctx.fillText(order.maijia, 29.5, 60.5);

    // 绘制副标题 "订单金额" - 字体较大
    ctx.setFillStyle('#999999');
    ctx.setFontSize(24);
    ctx.fillText('订单金额', 30, 100);

    // 绘制订单号 "(单号:xxx)" - 字体较小，并留有间距
    const labelWidth = ctx.measureText('订单金额').width;
    ctx.setFontSize(20);
    ctx.fillText(`（单号:${order.id}）`, 30 + labelWidth + 8, 100);

    // 绘制金额（大号绿色）- 加粗效果
    ctx.setFillStyle('#3abe2c');
    ctx.setFontSize(48);
    ctx.setTextAlign('left');
    const amountText = `¥${formatNumber(order.print_price || 0)}`;
    // 多次绘制模拟加粗
    ctx.fillText(amountText, 30, 160);
    ctx.fillText(amountText, 30.5, 160);
    ctx.fillText(amountText, 30, 160.5);
    ctx.fillText(amountText, 30.5, 160.5);

    // 绘制订单时间（精确到秒）
    const orderTime = `订单时间：${formatDateWithSeconds(order.add_time)}`;
    ctx.setFillStyle('#666666');
    ctx.setFontSize(18);
    ctx.fillText(orderTime, 30, 200);

    // 绘制底部绿色渐变按钮区域（带圆角）
    const btnX = 30;
    const btnY = canvasHeight.value - 70;
    const btnWidth = canvasWidth.value - 60;
    const btnHeight = 50;
    const btnRadius = 2;

    // 绘制圆角矩形
    ctx.beginPath();
    ctx.moveTo(btnX + btnRadius, btnY);
    ctx.lineTo(btnX + btnWidth - btnRadius, btnY);
    ctx.arcTo(btnX + btnWidth, btnY, btnX + btnWidth, btnY + btnRadius, btnRadius);
    ctx.lineTo(btnX + btnWidth, btnY + btnHeight - btnRadius);
    ctx.arcTo(
      btnX + btnWidth,
      btnY + btnHeight,
      btnX + btnWidth - btnRadius,
      btnY + btnHeight,
      btnRadius,
    );
    ctx.lineTo(btnX + btnRadius, btnY + btnHeight);
    ctx.arcTo(btnX, btnY + btnHeight, btnX, btnY + btnHeight - btnRadius, btnRadius);
    ctx.lineTo(btnX, btnY + btnRadius);
    ctx.arcTo(btnX, btnY, btnX + btnRadius, btnY, btnRadius);
    ctx.closePath();

    // 填充渐变色（135度,从青绿到草绿）
    const gradient = ctx.createLinearGradient(btnX, btnY, btnX + btnWidth, btnY + btnHeight);
    gradient.addColorStop(0.2, '#009481'); // 青绿色（20%）
    gradient.addColorStop(1, '#52b316'); // 草绿色（100%）
    ctx.setFillStyle(gradient);
    ctx.fill();

    // 绘制按钮文字
    ctx.setFillStyle('#ffffff');
    ctx.setFontSize(20);
    ctx.setTextAlign('center');
    ctx.fillText('查看订单详情', canvasWidth.value / 2, btnY + btnHeight / 2 + 6);

    // 绘制完成后，生成图片
    ctx.draw(false, () => {
      setTimeout(() => {
        uni.canvasToTempFilePath({
          canvasId: 'shareCanvas',
          success: (res) => {
            console.log('分享图片生成成功:', res.tempFilePath);
            orders.value[index].shareImageUrl = res.tempFilePath;
            orders.value[index].isGeneratingImage = false;
            resolve(res.tempFilePath);
          },
          fail: (err) => {
            console.error('生成图片失败:', err);
            orders.value[index].isGeneratingImage = false;
            reject(err);
          },
        });
      }, 300); // 延迟确保绘制完成
    });
  });
}

// 注册分享方法
onShareAppMessage(async (options: any) => {
  // 从 button 的 dataset 中获取订单索引
  if (
    options.from === 'button'
    && typeof options.target?.dataset?.orderIndex !== 'undefined'
  ) {
    const orderIndex = Number(options.target.dataset.orderIndex);
    const order = orders.value[orderIndex];

    if (!order) {
      return {
        title: '订单分享',
        path: '/pages/common/creditOrderList/creditOrderList',
      };
    }

    // 显示 loading
    uni.showLoading({
      title: '正在生成分享图片...',
      mask: true,
    });

    // 标记正在生成
    orders.value[orderIndex].isGeneratingImage = true;

    try {
      // 等待图片生成完成
      const imagePath = await createShareImage(order, orderIndex);

      uni.hideLoading();

      // 目标小程序的 appId 和路径
      const targetAppId = 'wx26980c7935e571cc';
      const storeId = userStore.userInfo?.admin_id || '';
      const storeName = encodeURIComponent(userStore.dangkou_name || '云批宝');
      const username = encodeURIComponent(userStore.user_name || '');

      // 获取买家ID
      const maijiaId = order.maijia_id
        || order.order_detail?.[0]?.maijia_id
        || order.fid
        || 0;

      // 构建小程序页面路径：跳转到 orderDetail 页面，传递完整订单数据
      // 参考 popupSheet.js 中的 onShareCurrent() 方法
      const orderInfoForTarget = {
        id: order.id,
        fid: order.fid || 0,
        order_num: order.order_num || '',
        piao_num: order.piao_num || order.orderId || '',
        maijia: order.maijia || order.buyerName || '',
        maijia_id: maijiaId,
        total_price: order.total_price || order.amount || 0,
        goods_price: order.goods_price || 0,
        shishou: order.shishou || 0,
        huan: order.huan || 0,
        youhui: order.youhui || 0,
        duoshou: order.duoshou || 0,
        huankuan_time: order.huankuan_time || '',
        fujiafei: order.fujiafei || '0.00',
        store_id: order.store_id || 0,
        shouyin_id: order.shouyin_id || 0,
        sell_id: order.sell_id || 0,
        shouqian_id: order.shouqian_id || 0,
        add_time: order.add_time || order.createTime || '',
        status: order.status || 0,
        pay_time: order.pay_time || order.add_time || '',
        pay_type: order.pay_type || 0,
        book_id: order.book_id || 0,
        zuofei: order.zuofei || 0,
        cash_num: order.cash_num || 0,
        wepay_num: order.wepay_num || 0,
        alipay_num: order.alipay_num || 0,
        union_num: order.union_num || 0,
        other_num: order.other_num || 0,
        notes: order.notes || '',
        order_type: order.order_type || '0',
        maijia_name: order.maijia || order.buyerName || '',
        sheqian: order.sheqian || 0,
        yourself: order.yourself || 0,
        print_price: order.print_price || order.yingshou || 0,
        yingshou: order.yingshou || 0,
        // 订单明细
        order_detail: order.order_detail || [],
        // 用户信息
        user: order.user || {},
        // 买家信息
        maijiainfo: order.maijiainfo || {},
        // 其他可能的字段
        imageUrl: order.imageUrl || null,
        update_time: order.update_time || '',
      };

      // 返回分享配置，直接跳转到目标小程序的 orderDetail 页面（绕过 redirect）
      // 参考 creditOrderList.vue 中的传参方式
      const detailPath = `/pages/orderDetail/orderDetail?orderInfo=${encodeURIComponent(JSON.stringify(orderInfoForTarget))}&maijia=${encodeURIComponent(order.maijia || order.buyerName || '')}&amount=${order.status !== 0 ? order.shishou : order.yingshou}&orderId=${order.id}&storeName=${storeName}&is_external=${order.maijiainfo?.is_external || ''}`;

      return {
        title: `${userStore.real_name || '商家'}`,
        path: `/pages/common/share/redirect?targetAppId=${targetAppId}&targetPath=${encodeURIComponent(detailPath)}&maijia=${encodeURIComponent(
          order.maijia,
        )}&amount=${order.print_price || 0}&orderId=${order.id}&shopName=${storeName}`,
        imageUrl: imagePath,
      };
    }
    catch (error) {
      uni.hideLoading();
      uni.showToast({
        title: '生成图片失败',
        icon: 'none',
      });
    }
  }

  // 默认分享内容
  return {
    title: '订单分享',
    path: '/pages/common/creditOrderList/creditOrderList',
  };
});
</script>

<style scoped lang="scss">
/* 日历弹窗样式覆盖 */
:deep(.u-popup) {
  flex: 0 !important;
}

.fixed-header {
  position: fixed;
  background-color: #fff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.header-placeholder {
  width: 100%;
}

.footer-bar {
  padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
}
</style>
